package com.my.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.my.apis.article.IArticleClient;
import com.my.model.article.pojos.ApArticle;
import com.my.model.common.dtos.ResponseResult;
import com.my.model.common.enums.AppHttpCodeEnum;
import com.my.model.user.dtos.UserFollowDto;
import com.my.model.user.pojos.ApUser;
import com.my.model.user.pojos.ApUserFan;
import com.my.model.user.pojos.ApUserFollow;
import com.my.user.mapper.ApUserFollowMapper;
import com.my.user.service.ApUserFanService;
import com.my.user.service.ApUserFollowService;
import com.my.user.service.ApUserService;
import com.my.utils.thread.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Transactional
@Service
public class ApUserFollowServiceImpl extends ServiceImpl<ApUserFollowMapper, ApUserFollow> implements ApUserFollowService {
    @Autowired
    private ApUserService apUserService;
    @Resource
    private IArticleClient iArticleClient;
    @Autowired
    private ApUserFanService apUserFanService;
    /**
     * 用户关注作者
     * @param dto
     * @return
     */
    @Override
    public ResponseResult followUser(UserFollowDto dto) {
        if(dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //获取当前登录用户信息
        ApUser threadUser = AppThreadLocalUtils.getUser();
        ApUser user = apUserService.getById(threadUser.getId());

        //关注
        if(dto.getOperation() == 0) {
            log.info("用户{}关注作者{}",user.getId(),dto.getAuthorId());
            //保存关注信息(用户角度)
            boolean success = saveFollow(dto, user);
            if(!success) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"保存关注信息失败");
            }

            //保存粉丝信息(创作者角度)
            boolean success1 = saveFans(dto, user);
            if(!success1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"保存粉丝信息失败");
            }
        }

        //取消关注
        if(dto.getOperation() == 1) {
            log.info("用户{}取消关注作者{}",user.getId(),dto.getAuthorId());
            boolean isCancel = cancelFollow(dto.getAuthorId(),user.getId());
            if(!isCancel) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"取消关注失败");
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存关注信息
     * @param dto
     * @param user
     * @return
     */
    private boolean saveFollow(UserFollowDto dto,ApUser user) {
        boolean flag = false;
        try {
            ApUserFollow apUserFollow = new ApUserFollow();
            //设置参数信息
            apUserFollow.setUserId(user.getId());
            //远程调用得到文章信息
            ApArticle apArticle = iArticleClient.getById(dto.getArticleId());
            if(apArticle != null) {
                apUserFollow.setFollowName(apArticle.getAuthorName());
            }
            apUserFollow.setFollowId(dto.getAuthorId());
            apUserFollow.setCreatedTime(new Date());
            apUserFollow.setIsNotice((short)0);
            apUserFollow.setLevel((short)0);
            save(apUserFollow);
            log.info("保存关注信息成功");

            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 保存粉丝信息
     * @param dto
     * @param user
     * @return
     */
    private boolean saveFans(UserFollowDto dto,ApUser user) {
        boolean flag = false;
        try {
            ApUserFan fan = new ApUserFan();
            fan.setUserId(dto.getAuthorId());
            fan.setFansId(user.getId());
            fan.setFansName(user.getName());
            fan.setCreatedTime(new Date());
            apUserFanService.increaseFan(fan);
            log.info("保存粉丝信息成功");

            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;
    }

    /**
     * 取消关注
     * @param authorId
     * @param id
     * @return
     */
    private boolean cancelFollow(Integer authorId, Integer id) {
        boolean flag = false;

        try {
            //1.删除关注信息
            LambdaQueryWrapper<ApUserFollow> folqw = new LambdaQueryWrapper<>();
            folqw.eq(id != null,ApUserFollow::getUserId,id);
            folqw.eq(authorId != null,ApUserFollow::getFollowId,authorId);
            remove(folqw);
            log.info("删除关注信息成功");

            //2.删除粉丝信息
            LambdaQueryWrapper<ApUserFan> fanlqw = new LambdaQueryWrapper<>();
            fanlqw.eq(authorId != null,ApUserFan::getUserId,authorId);
            fanlqw.eq(id != null,ApUserFan::getFansId,id);
            apUserFanService.remove(fanlqw);
            log.info("删除粉丝信息成功");

            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;
    }


    /**
     * 当前用户是否关注了该作者
     * @param userId
     * @param authorId
     * @return
     */
    @Override
    public ResponseResult getUserFollow(Integer userId, Integer authorId) {
        boolean flag = false;
        if(userId == null || authorId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        LambdaQueryWrapper<ApUserFollow> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ApUserFollow::getUserId,userId);
        lqw.eq(ApUserFollow::getFollowId,authorId);
        ApUserFollow apUserFollow = getOne(lqw);
        if(apUserFollow != null) {
            flag = true;
        }

        return ResponseResult.okResult(flag);
    }
}
